package com.qf.emp.controller;

import com.qf.emp.entity.User;
import com.qf.emp.service.UserService;
import com.qf.emp.service.impl.UserServiceImpl;
import com.qf.emp.utils.Constants;
import com.qf.emp.utils.MD5Utils;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.Map;

@WebServlet("/user")
public class UserController extends BaseServlet{

    public String login(HttpServletRequest request,HttpServletResponse response){
        //1.收参
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //2.调用业务逻辑实现登录
        UserService userService = new UserServiceImpl();
        User user = userService.login(username,password);
            if(user != null){
                //登录成功，存储在session作用域
                HttpSession session = request.getSession();
                session.setAttribute("loginUser",user);
                return Constants.REDIRECT + "/list.jsp";
            }
        return Constants.FORWARD + "login.jsp";
    }
    public String check(HttpServletRequest request, HttpServletResponse response) throws SQLException {
        //1.获取用户名
        String username = request.getParameter("username");

        if (username == null) {
            return Constants.FORWARD + "register.jsp"; //不能注册
        }
        //2.调用业务逻辑判断用户名是否存在
        UserService userService = new UserServiceImpl();
        boolean b = userService.checkedUser(username);
        //3.响应字符串  1 存在  0 不存在
        if (b) {
            //用户存在
            return Constants.FORWARD + "regiter.jsp";
        }
        return Constants.FORWARD + "/user?method=regist";
    }
    public String regist(HttpServletRequest request,HttpServletResponse response){
        //1.获取用户信息，将信息放到映射容器中
        Map<String, String[]> parameterMap = request.getParameterMap();
        User user = new User();
        try {
            BeanUtils.populate(user,parameterMap);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        user.setPassword(MD5Utils.md5(user.getPassword()));
        //3.调用用户的业务逻辑进行注册
        UserService userService = new UserServiceImpl();
        try {
            userService.registerUser(user);
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("registerMsg","注册失败！");
            return Constants.FORWARD+"/register.jsp";
        }
        return Constants.FORWARD + "/login.jsp";
    }
}

